<template>
  <div class="mydiv">
    <el-tabs v-model="activeName">
      <el-tab-pane label="登录" name="first">


        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password"></el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="code">
            <el-input  v-model="loginForm.code"></el-input>
            <el-image @click="createImageCode"
                :src="url"></el-image>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="login('loginForm')">立即登录</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="注册" name="second">
        <el-form ref="regForm" :rules="regRules" :model="regForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="regForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="regForm.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="repassword">
            <el-input type="password" v-model="regForm.repassword"></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="regForm.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
              <el-radio label="保密"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item  lable="所属区域">

            <el-cascader
                :props="props"
                v-model="value"
                :options="options"
                @change="handleChange"></el-cascader>

          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="reg('regForm')">立即注册</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>


      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script>
import cuuid from "uuid";

export default {
  name: "LoginVue",
  data() {
    //校验用户名是否被注册
    var checkNameUion = (rule, value, callback) => {
      //调用后台检查用户是否存在
      this.axios.get("auth/getUserByName",{params:{username:value}}).then(res=>{

        if (res.data.data!=null) {
          callback(new Error('该用户已经被注册!'));
        } else {
          callback();
        }
      })


    };
    //校验两次密码输入是否一致
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.regForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      url:'',
      props:{
        value:'id',
        label:'name'
      },
      value: [],
      options: [],
      activeName: 'first',
      regForm: {},//注册的用户对象
      loginForm: {},//登录的用户对象
      loginRules: {//登录的校验规则
        username:[
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password:[
          {required: true, message: '请输入密码', trigger: 'blur'},
        ]
      ,
      code:[
        {required: true, message: '请输入验证码', trigger: 'blur'},
      ],

      },
      regRules: {//注册的校验规则
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
          { validator: checkNameUion, trigger: 'blur' }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],

        repassword: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      birthday: [
        {required: true, message: '请选择日期', trigger: 'change'},
      ]
      ,
      gender: [
        {required: true, message: '请选择性别', trigger: 'change'},
      ],

      }
    }
  }, methods: {

     cityInit(){
       this.axios.get("auth/city/list").then(res=>{
         this.options=res.data.data;
       })
     },
    handleChange(value) {//三级联动改变时
       this.regForm.pid=value[0];
       this.regForm.cid=value[1];
       this.regForm.aid=value[2];

    },

    login(formName) {
      this.$refs[formName].validate((valid) => {
            if (valid) {
              this.axios.post("auth/login", this.loginForm).then(res => {
                if (res.data.code == 200) {
                  this.$message.success("登录成功");
                  this.$router.push("/");//跳转到项目首页
                 //存储到cookies
                  this.$cookies.set("token",res.data.data);//token存储到cookies
                  localStorage.setItem("username",this.loginForm.username);
                } else {
                  this.$message.error(res.data.msg);
                }
              })
            }
          }
          )

    },
    reg(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("/auth/reg", this.regForm).then(res => {
            if (res.data.code == 200) {
              this.$message.success("注册成功");
              this.activeName = 'first';//回到登录tabs
            } else {
              this.$message.error("注册失败");
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });



    },
    createImageCode(){//创建验证码
      let cuuid = require('uuid');//获取uuid 组件
      let uuid=cuuid.v1();//调用uuid 组件方法 产生随机的uuid
      this.loginForm.uuid=uuid;
      this.url=this.$baseURL+"auth/createImageCode?uuid="+uuid;
    }
  },created() {
    this.cityInit();
   this.createImageCode();
  }
}
</script>

<style scoped>
.mydiv {
  width: 500px;
  margin: 0 auto;
}
</style>